import Foundation
import Darwin

// Unix Socket 客户端测试函数
func sendToSocket(url: String) -> Bool {
    return sendToSocketGeneric(message: url)
}

// 查询任务详情
func sendTaskQuery(taskId: String) -> Bool {
    return sendToSocketGeneric(message: "TASK:\(taskId)")
}

// 查询任务列表
func sendListQuery() -> Bool {
    return sendToSocketGeneric(message: "LIST")
}

// 查询服务器状态
func sendStatusRequest() -> Bool {
    return sendToSocketGeneric(message: "STATUS")
}

// 通用 socket 通信函数
func sendToSocketGeneric(message: String) -> Bool {
    let socketPath = "/tmp/video_downloader.sock"
    
    // 创建客户端 socket
    let clientSocket = socket(AF_UNIX, SOCK_STREAM, 0)
    guard clientSocket != -1 else {
        print("Failed to create client socket: \(String(cString: strerror(errno)))")
        return false
    }
    
    defer { close(clientSocket) }
    
    // 设置服务器地址
    var serverAddr = sockaddr_un()
    serverAddr.sun_family = sa_family_t(AF_UNIX)
    
    let pathBytes = socketPath.utf8CString
    withUnsafeMutablePointer(to: &serverAddr.sun_path) { pathPtr in
        pathPtr.withMemoryRebound(to: CChar.self, capacity: pathBytes.count) { charPtr in
            _ = pathBytes.withUnsafeBufferPointer { buffer in
                memcpy(charPtr, buffer.baseAddress, buffer.count)
            }
        }
    }
    
    // 连接到服务器
    let connectResult = withUnsafePointer(to: &serverAddr) { ptr in
        ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddrPtr in
            connect(clientSocket, sockaddrPtr, socklen_t(MemoryLayout<sockaddr_un>.size))
        }
    }
    
    guard connectResult == 0 else {
        print("Failed to connect to socket server: \(String(cString: strerror(errno)))")
        print("Make sure the helper tool server is running with: vdh server")
        return false
    }
    
    // 发送消息
    let bytesToSend = message.count
    let bytesSent = send(clientSocket, message, bytesToSend, 0)
    
    guard bytesSent == bytesToSend else {
        print("Failed to send complete data to server")
        return false
    }
    
    // 读取服务器响应
    var buffer = [UInt8](repeating: 0, count: 2048)  // 增加缓冲区大小
    let bytesReceived = recv(clientSocket, &buffer, 2047, 0)
    
    if bytesReceived > 0 {
        buffer[bytesReceived] = 0
        if let response = String(bytes: buffer[0..<bytesReceived], encoding: .utf8) {
            print(response.trimmingCharacters(in: .whitespacesAndNewlines))
        }
    }
    
    return true
}

// 服务器管理函数
func isServerRunning() -> Bool {
    // 尝试连接到socket来检查服务器是否运行
    let socketPath = "/tmp/video_downloader.sock"
    let clientSocket = socket(AF_UNIX, SOCK_STREAM, 0)
    
    guard clientSocket != -1 else {
        return false
    }
    
    defer {
        close(clientSocket)
    }
    
    var serverAddr = sockaddr_un()
    serverAddr.sun_family = sa_family_t(AF_UNIX)
    
    let pathBytes = socketPath.utf8CString
    guard pathBytes.count <= MemoryLayout.size(ofValue: serverAddr.sun_path) else {
        return false
    }
    
    withUnsafeMutableBytes(of: &serverAddr.sun_path) { ptr in
        pathBytes.withUnsafeBufferPointer { pathPtr in
            ptr.copyMemory(from: UnsafeRawBufferPointer(pathPtr))
        }
    }
    
    let result = withUnsafePointer(to: serverAddr) { addrPtr in
        addrPtr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockAddrPtr in
            connect(clientSocket, sockAddrPtr, socklen_t(MemoryLayout<sockaddr_un>.size))
        }
    }
    
    return result == 0
}